/*************************************************************************
	> File Name: server.cpp
	> Author: 
	> Mail: 
	> Created Time: Thu 24 Sep 2020 03:36:09 PM CST
 ************************************************************************/

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/wait.h>
#include <strings.h>

using namespace std;

int MyRecv(int iSock, char* pchBuf, size_t tCount){
    size_t tByteRead = 0;
    int iThisRead;

    while(tByteRead < tCount){
        do{
            iThisRead = read(iSock, pchBuf, tCount - tByteRead);
        }while((iThisRead < 0) && (errno == EINTR));
        if(iThisRead < 0){
            return iThisRead;
        }
        else if(iThisRead == 0){
            return tByteRead;
        }
        tByteRead += iThisRead;
        pchBuf += iThisRead;
    }
}

#define DEFAULT_PORT 12000

int main(int argc, char** argv){
    int listenfd, acceptfd;
    struct sockaddr_in myaddr;
    struct sockaddr_in theiraddr;
    unsigned int sin_size, myport = 12000, lisnum = 10;

    if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
        perror("socket: ");
        return -1;
    }
    printf("socket OK!\n");
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(DEFAULT_PORT);
    myaddr.sin_addr.s_addr = INADDR_ANY;

    bzero(&(myaddr.sin_zero), 0);
    if(bind(listenfd, (struct sockaddr*)&myaddr, sizeof(struct sockaddr)) == -1){
        perror("bind: ");
        return -2;
    }
    printf("bind ok!\n");

    if(listen(listenfd, lisnum) == -1){
        perror("listen: ");
        return -3;
    }
    printf("listen ok!\n");

    char recvMsg[10];
    sin_size = sizeof(myaddr);
    acceptfd = accept(listenfd, (struct sockaddr*)&myaddr, &sin_size);
    if(acceptfd < 0){
        close(listenfd);
        printf("accept failed!\n");
        return -4;
    }

    ssize_t readLen = MyRecv(acceptfd, recvMsg, sizeof(int));
    if(readLen < 0){
        printf("read failed!\n");
        return -5;
    }

    int len = (int)ntohl(*(int*)recvMsg);
    printf("len: %d\n", len);
    readLen = MyRecv(acceptfd, recvMsg, len);
    if(readLen < 0){
        printf("read failed!\n");
        return -6;
    }
    recvMsg[len] = '\0';
    printf("recvMsg: %s\n", recvMsg);
    close(acceptfd);
    close(listenfd);

    return 0;
}

